from django.shortcuts import render, HttpResponse, redirect

from web.forms.account import *
from django.conf import settings
from utils.tencent.sms import send_sms_single
from django.http import JsonResponse
from django.http import HttpResponse
from django.shortcuts import render
import random
from io import BytesIO
from utils.image_code import check_code

# 执行复杂查询 使用 & ｜ 时
from django.db.models import Q

import uuid
from datetime import datetime


def send_sms(request):
    """
        发送短息
    :param request:
    :return:
    """

    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def register(request):
    """
        用户信息注册
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = RegisterModelForm(request)
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(request, data=request.POST)
    if form.is_valid():
        # 实现保存功能
        form.save()

        return JsonResponse({'status': True, 'data': '/web/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """
     根据手机验证码进行登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = loginSmsForm(request)
        return render(request, 'login_sms.html', {'form': form})
    form = loginSmsForm(request, data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        # 根据手机号查询用户信息
        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_obj.id
        request.session['username'] = user_obj.username
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/web/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """
        用户名密码登录功能
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = loginForm(request)
        return render(request, 'login.html', {'form': form})
    form = loginForm(request, data=request.POST)
    if form.is_valid():
        # 要去数据库进行校验
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_obj = models.UserInfo.objects \
            .filter(Q(email=username) | Q(mobile_phone=username)) \
            .filter(password=password) \
            .first()
        if user_obj:
            request.session['user_id'] = user_obj.id
            request.session['username'] = user_obj.username
            request.session.set_expiry(60 * 60 * 24 * 14)

            return redirect('/web/index/')

        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """
        生成图片验证码
    :param request:
    :return:
    """
    image_obj, code = check_code()
    # 将图片验证码保存到session中
    request.session['image_code'] = code
    request.session.set_expiry(60)

    stream = BytesIO()
    image_obj.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())


def logout(request):
    """
        用户退出
    :param request:
    :return:
    """
    request.session.flush()
    return redirect('/web/index/')



def custom_404_view(request, exception):
    return redirect('/web/index/')

